﻿using System;
using System.Windows.Forms;

namespace ypn.common.csharp
{
    /// <summary>
    /// 异常工具类
    /// </summary>
    public class ExceptionHelper
    {
        private static bool f_isShowMessage = false; //是否弹出显示系统错误提示

        /// <summary>
        /// 初始化全局异常捕获
        /// </summary>
        public static void Initialize(bool i_isShowMessage)
        {
            f_isShowMessage = i_isShowMessage;
            //设置应用程序处理异常方式：ThreadException处理
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //UI线程的未处理异常捕获
            Application.ThreadException += Application_ThreadException;
            //非UI线程的未处理异常捕获
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            //任何异常捕获
            //AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
        }

        //private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        //{
        //    LogHelper.WriteLog(e.Exception, "FirstChanceException");
        //    MessageBox.Show(e.Exception.ToString(), "系统错误");
        //}

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogHelper.WriteLog(e.ExceptionObject as Exception, "UnhandledException");
            if (f_isShowMessage)
            {
                MessageBox.Show(e.ExceptionObject.ToString(), "系统错误");
            }
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            LogHelper.WriteLog(e.Exception, "ApplicationException");
            if (f_isShowMessage)
            {
                MessageBox.Show(e.Exception.ToString(), "系统错误");
            }
        }
    }
}
